// 全局变量
let currentUser = null;
const API_BASE_URL = '/api';

// 页面加载完成后执行
$(document).ready(function() {
    // 检查是否已登录
    checkLoginStatus();

    // 注册表单提交事件
    $('#registerForm').on('submit', function(e) {
        e.preventDefault();
        register();
    });

    // 登录表单提交事件
    $('#loginForm').on('submit', function(e) {
        e.preventDefault();
        login();
    });

    // 退出登录按钮点击事件
    $('#logoutBtn').on('click', function() {
        logout();
    });

    // 创建活动表单提交事件
    $('#createActivityForm').on('submit', function(e) {
        e.preventDefault();
        createActivity();
    });
});

// 检查登录状态
function checkLoginStatus() {
    const user = localStorage.getItem('currentUser');
    if (user) {
        currentUser = JSON.parse(user);
        updateUI();
        loadActivities();
        if (currentUser.id) {
            loadMyCreatedActivities(currentUser.id);
            loadMyRegisteredActivities(currentUser.id);
        }
        if (currentUser.isAdmin) {
            loadAllUsers();
            loadAllActivities();
        }
    }
}

// 注册
function register() {
    const registerRequest = {
        username: $('#registerUsername').val(),
        password: $('#registerPassword').val(),
        name: $('#registerName').val(),
        email: $('#registerEmail').val(),
        phone: $('#registerPhone').val(),
        studentId: $('#registerStudentId').val()
    };

    $.ajax({
        url: API_BASE_URL + '/users/register',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(registerRequest),
        success: function(response) {
            if (response.code === 200) {
                alert('注册成功，请登录');
                $('#registerForm')[0].reset();
            } else {
                alert('注册失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('注册失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 登录
function login() {
    const loginRequest = {
        username: $('#loginUsername').val(),
        password: $('#loginPassword').val()
    };

    $.ajax({
        url: API_BASE_URL + '/users/login',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(loginRequest),
        success: function(response) {
            if (response.code === 200) {
                currentUser = response.data;
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                $('#loginForm')[0].reset();
                updateUI();
                loadActivities();
                if (currentUser.id) {
                    loadMyCreatedActivities(currentUser.id);
                    loadMyRegisteredActivities(currentUser.id);
                }
                if (currentUser.isAdmin) {
                    loadAllUsers();
                    loadAllActivities();
                }
            } else {
                alert('登录失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('登录失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 退出登录
function logout() {
    currentUser = null;
    localStorage.removeItem('currentUser');
    updateUI();
}

// 更新UI
function updateUI() {
    if (currentUser) {
        $('#userPanel').show();
        $('#userInfo').html(`
            <p><strong>用户名：</strong>${currentUser.username}</p>
            <p><strong>姓名：</strong>${currentUser.name || '未设置'}</p>
            <p><strong>邮箱：</strong>${currentUser.email || '未设置'}</p>
            <p><strong>手机：</strong>${currentUser.phone || '未设置'}</p>
            <p><strong>学号：</strong>${currentUser.studentId || '未设置'}</p>
        `);
        
        // 如果是管理员，显示管理员面板
        if (currentUser.isAdmin) {
            $('#adminPanel').show();
        } else {
            $('#adminPanel').hide();
        }
    } else {
        $('#userPanel').hide();
        $('#adminPanel').hide();
    }
}

// 加载活动列表
function loadActivities() {
    $.ajax({
        url: API_BASE_URL + '/activities/active',
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                displayActivities(response.data, '#activityList');
            } else {
                alert('获取活动列表失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('获取活动列表失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 加载我创建的活动
function loadMyCreatedActivities(userId) {
    $.ajax({
        url: API_BASE_URL + '/activities/creator/' + userId,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                displayActivities(response.data, '#myCreatedActivities');
            } else {
                alert('获取我创建的活动失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('获取我创建的活动失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 加载我报名的活动
function loadMyRegisteredActivities(userId) {
    $.ajax({
        url: API_BASE_URL + '/activities/registered/' + userId,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                displayActivities(response.data, '#myRegisteredActivities');
            } else {
                alert('获取我报名的活动失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('获取我报名的活动失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 显示活动列表
function displayActivities(activities, containerId) {
    const container = $(containerId);
    container.empty();

    if (activities.length === 0) {
        container.html('<p class="text-center">暂无活动</p>');
        return;
    }

    activities.forEach(function(activity) {
        const startTime = new Date(activity.startTime).toLocaleString();
        const endTime = new Date(activity.endTime).toLocaleString();
        const deadline = new Date(activity.registrationDeadline).toLocaleString();
        
        const card = `
            <div class="col-md-6 mb-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title">${activity.title}</h5>
                        <p class="card-text">${activity.description}</p>
                        <p><strong>地点：</strong>${activity.location}</p>
                        <p><strong>时间：</strong>${startTime} - ${endTime}</p>
                        <p><strong>报名截止：</strong>${deadline}</p>
                        <p><strong>人数：</strong>${activity.currentParticipants}/${activity.maxParticipants || '不限'}</p>
                        <p><strong>创建者：</strong>${activity.creatorName}</p>
                        ${containerId === '#activityList' ? 
                            `<button class="btn btn-primary register-btn" data-id="${activity.id}">报名</button>` : ''}
                        ${containerId === '#myRegisteredActivities' ? 
                            `<button class="btn btn-danger cancel-btn" data-id="${activity.id}">取消报名</button>` : ''}
                        ${containerId === '#myCreatedActivities' ? 
                            `<button class="btn btn-warning edit-btn" data-id="${activity.id}">编辑</button>
                             <button class="btn btn-danger delete-btn" data-id="${activity.id}">删除</button>` : ''}
                    </div>
                </div>
            </div>
        `;
        container.append(card);
    });

    // 绑定报名按钮事件
    $('.register-btn').on('click', function() {
        const activityId = $(this).data('id');
        registerForActivity(activityId, currentUser.id);
    });

    // 绑定取消报名按钮事件
    $('.cancel-btn').on('click', function() {
        const activityId = $(this).data('id');
        cancelRegistration(activityId, currentUser.id);
    });

    // 绑定编辑按钮事件
    $('.edit-btn').on('click', function() {
        const activityId = $(this).data('id');
        editActivity(activityId);
    });

    // 绑定删除按钮事件
    $('.delete-btn').on('click', function() {
        const activityId = $(this).data('id');
        deleteActivity(activityId);
    });
}

// 创建活动
function createActivity() {
    if (!currentUser || !currentUser.id) {
        alert('请先登录');
        return;
    }

    const activityRequest = {
        title: $('#activityTitle').val(),
        description: $('#activityDescription').val(),
        location: $('#activityLocation').val(),
        startTime: $('#activityStartTime').val(),
        endTime: $('#activityEndTime').val(),
        registrationDeadline: $('#activityDeadline').val(),
        maxParticipants: $('#activityMaxParticipants').val()
    };

    $.ajax({
        url: API_BASE_URL + '/activities?creatorId=' + currentUser.id,
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(activityRequest),
        success: function(response) {
            if (response.code === 200) {
                alert('活动创建成功');
                $('#createActivityForm')[0].reset();
                loadActivities();
                loadMyCreatedActivities(currentUser.id);
            } else {
                alert('活动创建失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('活动创建失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 报名活动
function registerForActivity(activityId, userId) {
    $.ajax({
        url: API_BASE_URL + '/activities/' + activityId + '/register/' + userId,
        type: 'POST',
        success: function(response) {
            if (response.code === 200) {
                alert('报名成功');
                loadActivities();
                loadMyRegisteredActivities(userId);
            } else {
                alert('报名失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('报名失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 取消报名
function cancelRegistration(activityId, userId) {
    $.ajax({
        url: API_BASE_URL + '/activities/' + activityId + '/register/' + userId,
        type: 'DELETE',
        success: function(response) {
            if (response.code === 200) {
                alert('取消报名成功');
                loadActivities();
                loadMyRegisteredActivities(userId);
            } else {
                alert('取消报名失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('取消报名失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 编辑活动
function editActivity(activityId) {
    // 获取活动详情并填充表单
    $.ajax({
        url: API_BASE_URL + '/activities/' + activityId,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const activity = response.data;
                // 这里可以实现编辑活动的逻辑
                alert('编辑功能待实现');
            } else {
                alert('获取活动详情失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('获取活动详情失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 删除活动
function deleteActivity(activityId) {
    if (confirm('确定要删除该活动吗？')) {
        $.ajax({
            url: API_BASE_URL + '/activities/' + activityId,
            type: 'DELETE',
            success: function(response) {
                if (response.code === 200) {
                    alert('活动删除成功');
                    loadActivities();
                    loadMyCreatedActivities(currentUser.id);
                } else {
                    alert('活动删除失败：' + response.message);
                }
            },
            error: function(xhr) {
                alert('活动删除失败：' + xhr.responseJSON?.message || '服务器错误');
            }
        });
    }
}

// 管理员功能：加载所有用户
function loadAllUsers() {
    $.ajax({
        url: API_BASE_URL + '/admin/users',
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                displayUsers(response.data);
            } else {
                alert('获取用户列表失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('获取用户列表失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 管理员功能：加载所有活动
function loadAllActivities() {
    $.ajax({
        url: API_BASE_URL + '/admin/activities',
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                displayAdminActivities(response.data);
            } else {
                alert('获取活动列表失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('获取活动列表失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
}

// 管理员功能：显示用户列表
function displayUsers(users) {
    const container = $('#usersList');
    container.empty();

    if (users.length === 0) {
        container.html('<p class="text-center">暂无用户</p>');
        return;
    }

    const table = `
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>姓名</th>
                    <th>邮箱</th>
                    <th>手机</th>
                    <th>学号</th>
                    <th>角色</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${users.map(user => `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.name || ''}</td>
                        <td>${user.email || ''}</td>
                        <td>${user.phone || ''}</td>
                        <td>${user.studentId || ''}</td>
                        <td>${user.isAdmin ? '管理员' : '普通用户'}</td>
                        <td>
                            <button class="btn btn-sm btn-danger delete-user-btn" data-id="${user.id}">删除</button>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    container.append(table);

    // 绑定删除用户按钮事件
    $('.delete-user-btn').on('click', function() {
        const userId = $(this).data('id');
        deleteUser(userId);
    });
}

// 管理员功能：显示活动列表
function displayAdminActivities(activities) {
    const container = $('#adminActivitiesList');
    container.empty();

    if (activities.length === 0) {
        container.html('<p class="text-center">暂无活动</p>');
        return;
    }

    const table = `
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>标题</th>
                    <th>创建者</th>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th>报名截止</th>
                    <th>人数</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${activities.map(activity => `
                    <tr>
                        <td>${activity.id}</td>
                        <td>${activity.title}</td>
                        <td>${activity.creatorName}</td>
                        <td>${new Date(activity.startTime).toLocaleString()}</td>
                        <td>${new Date(activity.endTime).toLocaleString()}</td>
                        <td>${new Date(activity.registrationDeadline).toLocaleString()}</td>
                        <td>${activity.currentParticipants}/${activity.maxParticipants || '不限'}</td>
                        <td>${activity.isActive ? '活跃' : '已关闭'}</td>
                        <td>
                            <button class="btn btn-sm btn-${activity.isActive ? 'warning' : 'success'} toggle-status-btn" 
                                    data-id="${activity.id}" 
                                    data-status="${!activity.isActive}">
                                ${activity.isActive ? '关闭' : '激活'}
                            </button>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    container.append(table);

    // 绑定切换活动状态按钮事件
    $('.toggle-status-btn').on('click', function() {
        const activityId = $(this).data('id');
        const newStatus = $(this).data('status');
        updateActivityStatus(activityId, newStatus);
    });
}

// 管理员功能：删除用户
function deleteUser(userId) {
    if (confirm('确定要删除该用户吗？')) {
        $.ajax({
            url: API_BASE_URL + '/admin/users/' + userId,
            type: 'DELETE',
            success: function(response) {
                if (response.code === 200) {
                    alert('用户删除成功');
                    loadAllUsers();
                } else {
                    alert('用户删除失败：' + response.message);
                }
            },
            error: function(xhr) {
                alert('用户删除失败：' + xhr.responseJSON?.message || '服务器错误');
            }
        });
    }
}

// 管理员功能：更新活动状态
function updateActivityStatus(activityId, isActive) {
    $.ajax({
        url: API_BASE_URL + '/admin/activities/' + activityId + '/status?isActive=' + isActive,
        type: 'PUT',
        success: function(response) {
            if (response.code === 200) {
                alert('活动状态更新成功');
                loadAllActivities();
            } else {
                alert('活动状态更新失败：' + response.message);
            }
        },
        error: function(xhr) {
            alert('活动状态更新失败：' + xhr.responseJSON?.message || '服务器错误');
        }
    });
} 